package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

/**
 * Created with IntelliJ IDEA.
 * 106. 从中序与后序遍历序列构造二叉树
 *
 * @author liw
 * @version 1.0
 * @date 2023/1/7 9:06
 */
public class BuildTree106 {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (postorder == null || postorder.length == 0) {
            return null;
        }
        int length = postorder.length - 1;
        TreeNode node = new TreeNode(postorder[length]);
        find(postorder, inorder, node, 0, length, 0, length);
        return node;
    }

    private void find(int[] postorder, int[] inorder, TreeNode node, int st, int end, int st2, int end2) {
        if (st > end) {
            return;
        }
        int value = postorder[end];
        int split = st2;
        for (int j = st2; j <= end2; j++) {
            if (inorder[j] == value) {
                split = j;
                break;
            }
        }
        int leftLength = split - st2;
        if (leftLength != 0) {
            TreeNode l = new TreeNode(postorder[st + leftLength - 1]);
            node.left = l;
            find(postorder, inorder, l, st, st + leftLength - 1, st2, split - 1);
        }
        if (split != end2) {
            TreeNode r = new TreeNode(postorder[end - 1]);
            node.right = r;
            find(postorder, inorder, r, st + leftLength, end - 1, split + 1, end2);
        }
    }

}
